package net.tycmc.cty.ctyms.timejob.common;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import net.tycmc.bulb.common.dao.ConnHelper;
import net.tycmc.bulb.common.dao.DetermineParamType;
import net.tycmc.bulb.dbutil.global.GlobalDBVar;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;

import com.microsoft.sqlserver.jdbc.SQLServerDataSource;
import com.tycmc.functions.util.MapGetter;

public class MyConnectDSTransDAO {
	private static Logger log = Logger.getLogger(MyConnectDSTransDAO.class);
	String ServerName;
	int PortNumber;
	String UserName;
	String Password;
	String DatabaseName;
	
	public MyConnectDSTransDAO(){
		try {
			ServerName = DynamicReadConfig.getConfigProperty("config.properties", "ServerName");
			PortNumber = Integer.parseInt(DynamicReadConfig.getConfigProperty("config.properties", "PortNumber"));
			UserName= DynamicReadConfig.getConfigProperty("config.properties", "UserName");
			Password= DynamicReadConfig.getConfigProperty("config.properties", "Password");
			DatabaseName= DynamicReadConfig.getConfigProperty("config.properties", "DatabaseName");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public MyConnectDSTransDAO(String ServerName,int PortNumber,String UserName,String Password,String DatabaseName){
		this.ServerName = ServerName;
		this.PortNumber = PortNumber;
		this.UserName= UserName;
		this.Password= Password;
		this.DatabaseName= DatabaseName;
	}
	
	//应用于统计定时任务向备份数据库插入统计结果
	public MyConnectDSTransDAO(boolean isTure){
		this.ServerName = MapGetter.getString(GlobalDBVar.dbMSBak,"ServerName");
		this.PortNumber = Integer.parseInt(MapGetter.getString(GlobalDBVar.dbMSBak,"PortNumber"));
		this.UserName= MapGetter.getString(GlobalDBVar.dbMSBak,"UserName");
		this.Password= MapGetter.getString(GlobalDBVar.dbMSBak,"Password");
		this.DatabaseName= MapGetter.getString(GlobalDBVar.dbMSBak,"DatabaseName");
	}
	
	/**
	 * 数据库链接
	 * @return
	 */
	public Connection getConnection(){
		SQLServerDataSource ds = new SQLServerDataSource();
        ds.setUser(UserName);
        ds.setPassword(Password);
        ds.setServerName(ServerName);
        ds.setPortNumber(PortNumber); 
        ds.setDatabaseName(DatabaseName);
        try {
			return ds.getConnection();
		} catch (Exception e) {
			e.printStackTrace();
		}
        return null;
	}
	
	/**
	 * 批量查询
	 * @param sqlList
	 * @param paramList
	 * @return
	 */
	public boolean batch(List<String> sqlList, List<Object[]> paramList){
		Connection conn = null;
		
		//验证参数是否可用
		if(null == sqlList || null == paramList){
			if(log.isDebugEnabled()){
				log.debug("SQL语句列表为空，或者，参数列表为空");
			}
			return false;
		}
		
		if(sqlList.size() <= 0 || paramList.size() <= 0){
			if(log.isDebugEnabled()){
				log.debug("SQL语句列表为空，或者，参数列表为空");
			}
			return false;
		}
		
		//SQL和参数表要匹配
		if(sqlList.size() != paramList.size()){
			if(log.isDebugEnabled()){
				log.debug("SQL语句列表数目 <>参数列表数目");
			}
			return false;
		}
		
		//取到连接
		conn = this.getConnection();
		
		try {
			conn.setAutoCommit(false);
			
			for(int i=0;i<sqlList.size();i++){
				String strSQL = sqlList.get(i);
				Object[] params = paramList.get(i);
				
				exec(conn, strSQL, params);
			}
			
			conn.commit();
			return true;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			log.error("执行SQL语句时发生错误。", e);
			
			try {
				if(log.isEnabledFor(Level.toLevel("warn"))){
					log.warn("开始进行事物回滚");
				}
				conn.rollback();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				log.error("事务回滚时发生了错误", e1);
			}
		}finally{
			try {
				conn.setAutoCommit(true);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				log.error("setAutoCommit=true时失败", e);
			}
			
			ConnHelper.close(conn);
		}
		
		return false;
	}

	/**
	 * @param conn
	 * @param strSQL
	 * @param params
	 * @return
	 * @throws Exception
	 * 
	 * 加入参数校验。当参数校验失败时，抛出错误。
	 */
	private static boolean exec(Connection conn, String strSQL,
			Object[] params) throws Exception {
		// TODO Auto-generated method stub
		if(null == strSQL){
			throw new Exception("没有给出SQL语句");
		}
		
		String trimdSQL = strSQL.trim().toLowerCase();
		if(trimdSQL.length() <= 0){
			throw new Exception("没有给出参数列表");
		}
		
		if(trimdSQL.startsWith("insert")){
			execInsert(conn, strSQL, params);
		}else if(trimdSQL.startsWith("update")){
			execUpdate(conn, strSQL, params);
		}else{
			execDefault(conn, strSQL, params);
			//throw new Exception("事务方法碰到暂时不能支持的sql语句。目前仅支持insert、update语句。");
		}
		
		return true;
	}
	
	private static void execDefault(Connection conn, String strSQL, Object[] params) throws Exception{
		PreparedStatement ps = null;
		
		try {
			ps = conn.prepareStatement(strSQL);
			for(int i=0;i<params.length;i++){
				DetermineParamType.determine(ps, i+1, params[i]);
			}
			
			ps.execute();
		} catch (Exception e) {
			log.error("执行以下SQL语句发生错误:"+toString(strSQL, params), e);
			throw e;
		}finally{
			ConnHelper.close(ps);
		}
	}
	
	private static int execUpdate(Connection conn, String strSQL, Object[] params) throws Exception{
		PreparedStatement ps = null;
		
		try {
			ps = conn.prepareStatement(strSQL);
			for(int i=0;i<params.length;i++){
				DetermineParamType.determine(ps, i+1, params[i]);
			}
			
			return ps.executeUpdate();
		} catch (Exception e) {
			log.error("执行以下SQL语句发生错误:"+toString(strSQL, params), e);
			throw e;
		}finally{
			ConnHelper.close(ps);
		}
	}
	
	private static int execInsert(Connection conn, String strSQL, Object[] params) throws Exception{
		PreparedStatement ps = null;
		try {
			ps = conn.prepareStatement(strSQL);
			for(int i=0;i<params.length;i++){
				DetermineParamType.determine(ps, i+1, params[i]);
			}
			
			return ps.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
			log.error("执行以下SQL语句发生错误:"+toString(strSQL, params), e);
			throw e;
		}finally{
			ConnHelper.close(ps);
		}
	}

	/* (non-Javadoc)
	 * @see net.tycmc.bulb.common.dao.ITransactionDAO#batch(java.util.List)
	 */
	public boolean batch(List<String> sqlList){
		Connection connection=null;
		Statement stmt = null;
		
		//检查参数
		if (sqlList==null || sqlList.size()<=0){
			if(log.isDebugEnabled()){
				log.debug("SQL语句列表为空");
			}
			return false;
		}
		
		for(String sqlStr : sqlList){
			if (sqlStr == null || "".equals(sqlStr.trim())){
				if(log.isDebugEnabled()){
					log.debug("SQL语句列表中某条SQL语句为空");
				}
				return false;
			}
		}
		
		connection = this.getConnection();
		
		//将自动提交方式设为fasle，如果设置失败关闭连接，返回false。
		try {
			connection.setAutoCommit(false);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.error("setAutoCommit=false时失败", e);
			ConnHelper.close(connection);
			return false;
		}
		
		try {
			stmt=connection.createStatement();
			
			//批量添加语句
			for (String sqlStr : sqlList){
				stmt.addBatch(sqlStr);
			}
			
			//一次性提交语句
			int[] updateCounts = stmt.executeBatch();
			connection.commit();
			
			return true;
		} catch (Exception ex){
			log.error("执行下面的语句时发生错误："+sqlList.toString(), ex);//记录错误到日志
			
			//批量提交失败，进行事物回滚
			try {
				if(log.isEnabledFor(Level.toLevel("warn"))){
					log.warn("开始进行事物回滚");
				}
				connection.rollback();
			} catch (Exception ex1){
				log.error("事务回滚时发生了错误", ex1);
			}
		}finally{
			//setAutoCommit=true
			try {
				connection.setAutoCommit(true);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				log.error("setAutoCommit=true时失败", e);
			}
			
			//close
			ConnHelper.close(stmt);
			ConnHelper.close(connection);
		}
		
		return false;
	}
	
	private static String toString(String strSQL, Object[] params){
		StringBuilder sb = new StringBuilder();
		sb.append(strSQL);
		sb.append("\n");
		for(Object param:params){
			if(param instanceof String){
				sb.append((String)param);
			}else{
				sb.append(param);
			}
			sb.append("\t");
		}
		
		return sb.toString();
	}
	
	public static void main(String[] args) {
		MyConnectDSTransDAO d = new MyConnectDSTransDAO();
//		List<String> sql = new ArrayList<String>();
//		List<Object[]> params = new ArrayList<Object[]>();
//		String SQL2 = "insert into VclDB2_201410 values(?,?,?,?,getdate())";
//		sql.add(SQL2);
//		params.add(new Object[]{77,77,77,77});
//		sql.add(SQL2);
//		params.add(new Object[]{88,88,88,88});
//		sql.add(SQL2);
//		params.add(new Object[]{99,99,99,99});
//		sql.add(SQL2);
//		params.add(new Object[]{00,00,00,00});
//		boolean flag = d.batch(sql, params);
//		System.out.println(flag);
		
		List<String> sql = new ArrayList<String>();
		List<Object[]> params = new ArrayList<Object[]>();
		String SQL2 = "update VclDB2_201410 set VclDB2_BD_ID=? where VclDB2_ID=?";
		sql.add(SQL2);
		params.add(new Object[]{-3,1});
		sql.add(SQL2);
		params.add(new Object[]{-4,2});
		sql.add(SQL2);
		params.add(new Object[]{-5,3});
		sql.add(SQL2);
		params.add(new Object[]{-6,4});
		boolean flag = d.batch(sql, params);
		System.out.println(flag);
		
	}
}
